package de.sdc.mario.engine.sonar;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;

public class PlaySpcTest {

	private static SpcEmu mEmu;
	private static SourceDataLine line;
	private static AudioFormat format;
	private static DataLine.Info info;
	private final static int sampleRate = 32000;

	public static void main(String args[]) throws IOException, LineUnavailableException {

		FileInputStream fis = new FileInputStream("res/mus/smw-16a.spc");
		ByteArrayOutputStream buffer = new ByteArrayOutputStream();
		int nRead;
		byte[] data = new byte[16384];
		while ((nRead = fis.read(data, 0, data.length)) != -1) {
			buffer.write(data, 0, nRead);
		}
		buffer.flush();
		fis.close();
		
		byte[] spcData = buffer.toByteArray();
		
		mEmu = new SpcEmu();
		mEmu.setSampleRate(sampleRate);
		mEmu.loadFile(spcData);
		mEmu.startTrack();
		
		//Wenn nicht gesetzt, spiele Maximum
		//mEmu.setFadeMs(fadeOutStart, fadeOutLength);
		
		format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, sampleRate, 16, 2, 4, sampleRate, true);
		info = new DataLine.Info(SourceDataLine.class, format);
		
		line = (SourceDataLine) AudioSystem.getLine(info);
		line.open(format);
		line.start();
		
		byte[] b = new byte[8192];
		while (!mEmu.trackEnded()) {
            int count = mEmu.play(b, b.length / 2);
            line.write(b, 0, count * 2);
            System.out.println(mEmu.currentTime());
		}
		line.stop();
		line.close();
    }
}
